package com.zhuhjay.app.web.controller.wxmp;

import com.zhuhjay.common.base.exception.ApiLimiterException;
import com.zhuhjay.common.base.exception.BasicBusinessException;
import com.zhuhjay.common.web.annotation.NotHttpResult;
import com.zhuhjay.common.wxmp.builder.TextBuilder;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.mp.api.WxMpMessageRouter;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * @author ZhuHJay
 * @date 2023/8/2 20:47
 */
@Slf4j
@Api(tags = "微信公众号接入")
@RestController
@RequestMapping("wx/callback")
public class WxMpPortalController {

    @Resource
    private WxMpService wxService;
    @Resource
    private WxMpMessageRouter messageRouter;

    @GetMapping
    @ApiOperation("公众号接入调用")
    @NotHttpResult
    public String authGet(@RequestParam(name = "signature", required = false) String signature,
                          @RequestParam(name = "timestamp", required = false) String timestamp,
                          @RequestParam(name = "nonce", required = false) String nonce,
                          @RequestParam(name = "echostr", required = false) String echostr) {

        log.info("\n接收到来自微信服务器的认证消息：[{}, {}, {}, {}]",
                signature, timestamp, nonce, echostr);
        if (StringUtils.isAnyBlank(signature, timestamp, nonce, echostr)) {
            throw new BasicBusinessException("请求参数非法，请核实!");
        }
        if (wxService.checkSignature(timestamp, nonce, signature)) {
            return echostr;
        }
        return "非法请求";
    }

    @PostMapping(produces = "application/xml; charset=UTF-8")
    @ApiOperation("接收消息")
    @NotHttpResult
    public String post(@RequestBody String body,
                       @RequestParam("signature") String signature,
                       @RequestParam("timestamp") String timestamp,
                       @RequestParam("nonce") String nonce,
                       @RequestParam("openid") String openid,
                       @RequestParam(name = "encrypt_type", required = false) String encType,
                       @RequestParam(name = "msg_signature", required = false) String msgSignature) {

        /*log.info("\n接收微信请求：[openid=[{}], [signature=[{}], encType=[{}], msgSignature=[{}],"
                        + " timestamp=[{}], nonce=[{}], body=[\n{}\n] ",
                openid, signature, encType, msgSignature, timestamp, nonce, body);*/

        if (!wxService.checkSignature(timestamp, nonce, signature)) {
            throw new BasicBusinessException("非法请求，可能属于伪造的请求！");
        }

        String out = null;
        if (encType == null) {
            // 明文传输的消息
            WxMpXmlMessage inMessage = WxMpXmlMessage.fromXml(body);
            WxMpXmlOutMessage outMessage = route(inMessage);
            if (outMessage == null) {
                return "success";
            }
            out = outMessage.toXml();
        } else if ("aes".equalsIgnoreCase(encType)) {
            // aes加密的消息
            WxMpXmlMessage inMessage = WxMpXmlMessage.fromEncryptedXml(
                    body, wxService.getWxMpConfigStorage(),
                    timestamp, nonce, msgSignature
            );
            WxMpXmlOutMessage outMessage = route(inMessage);
            if (outMessage == null) {
                return "success";
            }
            out = outMessage.toEncryptedXml(wxService.getWxMpConfigStorage());
        }
        return out;
    }

    /** 消息路由 */
    private WxMpXmlOutMessage route(WxMpXmlMessage message) {
        try {
            return messageRouter.route(message);
        } catch (ApiLimiterException e) {
            return new TextBuilder().build(e.getMessage(), message, wxService);
        } catch (Exception e) {
            log.error("路由消息时出现异常！", e);
        }
        return null;
    }

}
